package org.goldfish.distributed_framework.registry.handlers;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public abstract class BaseHandler implements HttpHandler {

    protected String pattern;

    public BaseHandler(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        String path = exchange.getRequestURI().getPath();
        System.out.println("接收到请求: " + method + " " + path);
        System.out.println("\t请求头: " + exchange.getRequestHeaders());
        String extractedBody = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
        System.out.println("\t请求体: " + extractedBody);

        try {
            doHandle(exchange, extractedBody);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈
            sendResponse(exchange, 500, "Internal Server Error");
        }
    }

    protected abstract void doHandle(HttpExchange exchange, String extractedBody) throws IOException;

    protected void sendResponse(HttpExchange exchange, int code, String body) throws IOException {
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        exchange.sendResponseHeaders(code, bytes.length);
        OutputStream os = exchange.getResponseBody();
        os.write(bytes);
        os.close();
        System.out.println("发送响应: 状态码=" + code + ", 消息体=" + body);
    }
}
